'use client'

import { useState, useEffect } from 'react'
import { Plus, Search, Edit, Trash2, FolderOpen, FileText, Users, Calendar, Loader2, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { categoriesAPI } from '@/lib/api'
import { toast } from 'sonner'
import { 
  CompactLayout, 
  CompactHeading, 
  CompactSubheading,
  CompactGrid,
  CompactCard 
} from '@/components/ui/compact-layout'

interface Category {
  id: string
  name: string
  slug: string
  description?: string
  color: string
  icon?: string
  order: number
  parentId?: string
  createdAt: string
  updatedAt: string
  createdBy: {
    id: string
    username: string
  }
  children?: Category[]
  parent?: {
    id: string
    name: string
    slug: string
  }
  _count?: {
    knowledgeBases: number
    children: number
  }
  // 🔴 兼容字段，用于显示
  articlesCount?: number
  usersCount?: number
}

export default function CategoryManagement() {
  const [categories, setCategories] = useState<Category[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingCategory, setEditingCategory] = useState<Category | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formData, setFormData] = useState({
    name: '',
    slug: '',
    description: '',
    color: '#3B82F6',
    icon: '',
    order: 0,
    parentId: ''
  })

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      setIsLoading(true)
      const response = await categoriesAPI.getCategories({ includeStats: true })
      // 🔴 修复：根据后端接口响应格式，数据在 response 中
      setCategories(response || [])
    } catch (error: any) {
      console.error('Failed to fetch categories:', error)
      toast.error(error.message || '获取分类列表失败')
    } finally {
      setIsLoading(false)
    }
  }

  // 创建分类
  const createCategory = async () => {
    try {
      setIsSubmitting(true)
      await categoriesAPI.createCategory(formData)
      toast.success('分类创建成功')
      setShowAddForm(false)
      resetForm()
      // 🔴 确保创建成功后重新获取数据
      await fetchCategories()
    } catch (error: any) {
      console.error('Failed to create category:', error)
      toast.error(error.message || '创建分类失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 更新分类
  const updateCategory = async () => {
    if (!editingCategory) return

    try {
      setIsSubmitting(true)
      await categoriesAPI.updateCategory(editingCategory.id, formData)
      toast.success('分类更新成功')
      setEditingCategory(null)
      resetForm()
      // 🔴 确保更新成功后重新获取数据
      await fetchCategories()
    } catch (error: any) {
      console.error('Failed to update category:', error)
      toast.error(error.message || '更新分类失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 删除分类
  const deleteCategory = async (categoryId: string) => {
    if (!confirm('确定要删除这个分类吗？此操作不可撤销。')) {
      return
    }

    try {
      setIsSubmitting(true)
      await categoriesAPI.deleteCategory(categoryId)
      toast.success('分类删除成功')
      // 🔴 确保删除成功后重新获取数据
      await fetchCategories()
    } catch (error: any) {
      console.error('Failed to delete category:', error)
      toast.error(error.message || '删除分类失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: '',
      slug: '',
      description: '',
      color: '#3B82F6',
      icon: '',
      order: 0,
      parentId: ''
    })
  }

  // 编辑分类
  const handleEdit = (category: Category) => {
    setEditingCategory(category)
    setFormData({
      name: category.name,
      slug: category.slug,
      description: category.description || '',
      color: category.color,
      icon: category.icon || '',
      order: category.order,
      parentId: category.parentId || ''
    })
  }

  // 取消编辑
  const handleCancel = () => {
    setShowAddForm(false)
    setEditingCategory(null)
    resetForm()
  }

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (editingCategory) {
      updateCategory()
    } else {
      createCategory()
    }
  }

  // 初始化加载
  useEffect(() => {
    fetchCategories()
  }, [])

  const filteredCategories = categories.filter(category =>
    category.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (category.description && category.description.toLowerCase().includes(searchQuery.toLowerCase()))
  )

  // 🔴 修复：使用正确的字段计算统计数据
  const totalArticles = categories.reduce((sum, c) => sum + (c._count?.knowledgeBases || c.articlesCount || 0), 0)
  const totalUsers = categories.reduce((sum, c) => sum + (c._count?.children || c.usersCount || 0), 0)
  const activeCategories = categories.filter(c => !c.parentId) // 顶级分类视为启用状态

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin" />
          <span>加载分类数据中...</span>
        </div>
      </div>
    )
  }

  return (
    <CompactLayout spacing="md" padding="md">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <CompactHeading>分类管理</CompactHeading>
          <CompactSubheading>管理知识库内容分类</CompactSubheading>
        </div>
        <Button onClick={() => setShowAddForm(true)}>
          <Plus className="h-4 w-4 mr-2" />
          添加分类
        </Button>
      </div>

      {/* 分类统计 */}
      <CompactGrid cols={4}>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <FolderOpen className="h-4 w-4 text-blue-600" />
            <div>
              <p className="text-xs text-muted-foreground">总分类数</p>
              <p className="text-xl font-bold">{categories.length}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <FileText className="h-4 w-4 text-green-600" />
            <div>
              <p className="text-xs text-muted-foreground">总文章数</p>
              <p className="text-xl font-bold">{totalArticles}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <Users className="h-4 w-4 text-purple-600" />
            <div>
              <p className="text-xs text-muted-foreground">子分类数</p>
              <p className="text-xl font-bold">{totalUsers}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <Calendar className="h-4 w-4 text-orange-600" />
            <div>
              <p className="text-xs text-muted-foreground">顶级分类</p>
              <p className="text-xl font-bold">{activeCategories.length}</p>
            </div>
          </div>
        </CompactCard>
      </CompactGrid>

      {/* 搜索 */}
      <CompactCard>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold">搜索分类</h3>
        </div>
        <div className="relative">
          <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="搜索分类名称或描述..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-8 h-8"
          />
        </div>
      </CompactCard>

      {/* 分类列表 */}
      <CompactCard>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold">分类列表 ({filteredCategories.length})</h3>
        </div>
        {filteredCategories.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            暂无分类数据
          </div>
        ) : (
          <CompactGrid cols={3}>
            {filteredCategories.map((category) => (
              <div
                key={category.id}
                className="p-3 border border-border rounded-lg hover:shadow-md transition-shadow"
              >
                <div className="flex items-start justify-between mb-2">
                  <div className="flex items-center space-x-2">
                    <div 
                      className="w-3 h-3 rounded-full"
                      style={{ backgroundColor: category.color }}
                    />
                    <h3 className="font-medium text-sm">{category.name}</h3>
                  </div>
                  <div className="flex items-center space-x-2">
                    {/* 🔴 显示分类层级状态 */}
                    {category.parentId ? (
                      <Badge variant="secondary" className="text-xs">子分类</Badge>
                    ) : (
                      <Badge variant="default" className="bg-green-100 text-green-800 text-xs">顶级分类</Badge>
                    )}
                  </div>
                </div>
                
                <p className="text-xs text-muted-foreground mb-2 line-clamp-2">
                  {category.description || '暂无描述'}
                </p>
                
                <div className="flex items-center justify-between text-xs text-muted-foreground mb-2">
                  <span>别名: {category.slug}</span>
                  <span>创建: {new Date(category.createdAt).toLocaleDateString()}</span>
                </div>
                
                <div className="flex items-center justify-between text-xs">
                  <div className="flex items-center space-x-3">
                    <span className="flex items-center space-x-1">
                      <FileText className="h-3 w-3" />
                      <span>{category._count?.knowledgeBases || category.articlesCount || 0}</span>
                    </span>
                    <span className="flex items-center space-x-1">
                      <Users className="h-3 w-3" />
                      <span>{category._count?.children || category.usersCount || 0}</span>
                    </span>
                  </div>
                  
                  <div className="flex items-center space-x-1">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEdit(category)}
                      disabled={isSubmitting}
                      className="h-6 w-6 p-0"
                    >
                      <Edit className="h-3 w-3" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="text-destructive hover:text-destructive h-6 w-6 p-0"
                      onClick={() => deleteCategory(category.id)}
                      disabled={isSubmitting}
                    >
                      <Trash2 className="h-3 w-3" />
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </CompactGrid>
        )}
      </CompactCard>

      {/* 添加/编辑分类表单 */}
      {(showAddForm || editingCategory) && (
        <CompactCard>
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-lg font-semibold">
              {editingCategory ? '编辑分类' : '添加分类'}
            </h3>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleCancel}
              disabled={isSubmitting}
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
          <form onSubmit={handleSubmit} className="space-y-3">
            <div className="grid gap-3 md:grid-cols-2">
              <div>
                <label className="text-xs font-medium">分类名称</label>
                <Input
                  placeholder="输入分类名称"
                  value={formData.name}
                  onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                  className="mt-1 h-8"
                  required
                />
              </div>
              <div>
                <label className="text-sm font-medium">别名</label>
                <Input
                  placeholder="输入别名（英文）"
                  value={formData.slug}
                  onChange={(e) => setFormData(prev => ({ ...prev, slug: e.target.value }))}
                  className="mt-1 h-8"
                  required
                />
              </div>
            </div>
            
            <div>
              <label className="text-xs font-medium">描述</label>
              <Input
                placeholder="输入分类描述"
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                className="mt-1 h-8"
              />
            </div>
            
            <div className="grid gap-3 md:grid-cols-3">
              <div>
                <label className="text-xs font-medium">颜色</label>
                <Input
                  type="color"
                  value={formData.color}
                  onChange={(e) => setFormData(prev => ({ ...prev, color: e.target.value }))}
                  className="mt-1 h-8"
                />
              </div>
              <div>
                <label className="text-xs font-medium">图标</label>
                <Input
                  placeholder="输入图标名称"
                  value={formData.icon}
                  onChange={(e) => setFormData(prev => ({ ...prev, icon: e.target.value }))}
                  className="mt-1 h-8"
                />
              </div>
              <div>
                <label className="text-xs font-medium">排序</label>
                <Input
                  type="number"
                  placeholder="0"
                  value={formData.order}
                  onChange={(e) => setFormData(prev => ({ ...prev, order: parseInt(e.target.value) || 0 }))}
                  className="mt-1 h-8"
                />
              </div>
            </div>
            
            <div className="flex items-center justify-end space-x-2">
              <Button
                type="button"
                variant="outline"
                onClick={handleCancel}
                disabled={isSubmitting}
                size="sm"
              >
                取消
              </Button>
              <Button type="submit" disabled={isSubmitting} size="sm">
                {isSubmitting ? (
                  <>
                    <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                    {editingCategory ? '更新中...' : '创建中...'}
                  </>
                ) : (
                  editingCategory ? '更新' : '创建'
                )}
              </Button>
            </div>
          </form>
        </CompactCard>
      )}
    </CompactLayout>
  )
}
